const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const jwt = require('jsonwebtoken'); //引用jwt
//生成一个随机盐
const salt = crypto.randomBytes(16).toString('hex');


const secretKey = 'pp7_secret_key'; //密钥
const generateToken = (userId, username) => {
    const payload = {
        userId,
        username
    };
    const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
    return token;
}

function userRouteModule(db) {

    //注册接口
    router.post('/register', async (req, res) => {
        const { username, password } = req.body;
        //创建哈希值
        const hash = crypto.createHmac('sha256', salt).update(password).digest('hex');
        const sql = 'INSERT INTO user (username,password,salt) VALUES (?,?,?)'

        try {
            const [rows] = await db.query('select * fromm user where username = ?', [username]);
            if (rows.length > 0) {
                return res.status(401).send({ code: 401, message: '用户名已存在' });
            }

            const [result] = await db.query(sql, [username, hash, salt]);
            console.log(result, "result")
            res.status(200).send({ code: 200, msg: '注册成功' });

        } catch (error) {
            console.log(error, "错误");
            res.status(500).send({ code: 500, msg: '服务器错误' });
        }
    })


    // 登录接口
    router.post('/login', async (req, res) => {
        const { username, password } = req.body;

        try {
            const [rows] = await pool.promise().execute(
                'SELECT id, salt, password FROM users WHERE username = ?',
                [username]
            );

            if (rows.length === 0) {
                return res.status(401).send({ message: '用户名或密码错误' });
            }

            const storedSalt = rows[0].salt;
            const storedHash = rows[0].password;
            const id = rows[0].id;

            // 使用相同的盐对输入的密码进行哈希处理
            const hash = bcrypt.hashSync(password, storedSalt);

            // 比较新生成的哈希值与数据库中存储的哈希值
            if (hash !== storedHash) {
                return res.status(401).send({ message: '用户名或密码错误' });
            }

            // 登录成功，生成 JWT
            const token = generateToken(id);

            // 返回 JWT
            res.header('Authorization', token).send({ message: '登录成功', data: { token: token } });
        } catch (error) {

        }
    })



    return router;
}





module.exports = userRouteModule;